/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    ListNode *gHead;
    TreeNode *buildTree(int n) {
        if (n<=0) return NULL;
        TreeNode *ret=new TreeNode(-1);
        ret->left=buildTree(n/2);
        ret->val=gHead->val;
        gHead=gHead->next;
        ret->right=buildTree(n-n/2-1);
        return ret;
    }
public:
    TreeNode *sortedListToBST(ListNode *head) {
        gHead=head;
        int n=0;
        while (head!=NULL) {
            ++n;
            head=head->next;
        }
        return buildTree(n);
    }
};
